<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="平台" v-bind="validateInfos.platform">
	          <j-dict-select-tag
              v-model:value="formData.platform"
              dictCode="platform"
              :showChooseOption="false"
              placeholder="请选择平台"
              :disabled="disabled"
              :isShowAll="false"
              :noShowList="['0', '3']"
              :currMenu="'appVersion'"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="消息类型" v-bind="validateInfos.messageType">
            <a-select
              v-model:value="formData.messageType"
              :disabled="disabled"
              placeholder="请选择消息类型"
              @change="messageTypeChange"
            >
              <a-select-option :value="1">小说推荐</a-select-option>
              <a-select-option :value="2">活动推荐</a-select-option>
              <a-select-option :value="3">系统消息</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.messageType===1">
          <a-form-item label="小说ID" v-bind="validateInfos.messageTitle" key="messageTitle">
            <a-input v-model:value="formData.messageTitle" placeholder="请输入小说ID" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.messageType===2">
          <a-form-item label="图片" v-bind="validateInfos.img" key="img">
            <j-image-upload  v-model:value="formData.img" :disabled="disabled"></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.messageType!==1">
          <a-form-item label="消息标题" v-bind="validateInfos.messageTitle" key="messageTitle1">
            <a-input v-model:value="formData.messageTitle" placeholder="请输入消息标题" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="消息内容" v-bind="validateInfos.messageContent">
            <a-input v-model:value="formData.messageContent" placeholder="请输入消息内容" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="H5链接" v-bind="validateInfos.messageH5" v-if="formData.messageType===2" key="messageH5">
            <a-input v-model:value="formData.messageH5" placeholder="请输入H5链接" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>

      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../AppMessagePlan.api';
  import { Form } from 'ant-design-vue';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    isCopy: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    platform: '',
    messageType: 1,
    messageTitle: '',
    messageContent: '',
    releaseStatus: undefined,
    messageH5: '',
    img: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const validateH5 = async (rule, value) => {
    if (value === '') {
      return Promise.reject('请输入H5链接!');
    } else {
      let flag
      if (formData.platform===0){
        flag=value.startsWith('https://www.novelshome.com')
      }else if (formData.platform===1){
        flag=value.startsWith('https://www.novelworm.com')
      }else{
        flag=value.startsWith('https://www.vermenovela.com')
      }
      if (flag){
        return Promise.resolve();
      }else {
        return Promise.reject('请输入平台域名!');
      }

    }
  };
  //表单验证
  const validatorRules = {
    platform: [{ required: true, message: '请选择平台!'},],
    messageType: [{ required: true, message: '请选择消息类型!'},],
    messageTitle: [{ required: true, message: '请输入内容!'},],
    img: [{ required: true, message: '请选择图片!'},],
    messageContent: [{ required: true, message: '请输入消息内容!'},],
    messageH5: [{ required: true,validator: validateH5,},],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });



  function messageTypeChange(val) {
    console.log(val)
  }


  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    let validArr=['platform','messageType','messageTitle','messageContent']
    if (formData.messageType===2){
      validArr.push('img','messageH5')
    }
    await validate(validArr);
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    if (props.isCopy){
      model.id=''
    }
    let flag=false
    if (isUpdate.value){
      if (props.isCopy){
        flag=false
      }else {
        flag=true
      }
    }
    await saveOrUpdate(model, flag)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
</style>
